package com.zerdoor.service.impl;

import com.zerdoor.dao.ITaskInfoDao;
import com.zerdoor.service.ICommonPayService;
import com.zerdoor.service.ITaskInfoService;
import com.zerdoor.util.exception.FeeCardNotEnoughException;
import com.zerdoor.util.exception.InsufficientBalanceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhongjieyu on 2014/11/3.
 * 项目任务 业务层实现类
 */
@Service
public class TaskInfoServiceImpl implements ITaskInfoService{

    @Autowired
    private ITaskInfoDao taskInfoDao;

    @Autowired
    private ICommonPayService commonPayService;

    @Override
    public Map<String, Object> findInitData(int userId) throws Exception {

        //查询需求风格
        List<Map<String, String>> styleList = taskInfoDao.findMinorCodeByMajorid(103);

        //查询需求技能
        List<Map<String, String>> skillList = taskInfoDao.findMinorCodeByMajorid(104);

        //查询增值服务
        List<Map<String, String>> addValue = taskInfoDao.findAddValue();

        //查询零手续费卡数量
        int fee_num = taskInfoDao.findUserFeeNumByUserId(userId);

        Map<String,Object> dataMap = new HashMap<String, Object>();

        dataMap.put("styleList",styleList);
        dataMap.put("skillList",skillList);
        dataMap.put("addValue",addValue);
        dataMap.put("fee_num",fee_num);

        return dataMap;
    }

    @Override
    public List<Map<String, String>> findSkillBySkillIds(String skillIds) throws Exception {


        return taskInfoDao.findSkillBySkillIds(skillIds);
    }

    @Override
    public void addTaskInfoAndAddvalue(Map<String, String> param) throws Exception {

        //插入任务信息表
        taskInfoDao.addTaskInfo(param);

        //插入主订单表
        //taskInfoDao.addOrderMain(param);

        String user_id = param.get("user_id");

        //根据用户id查找推荐人id
        String presenter = taskInfoDao.findPresenterByUserId(user_id);

        //如果推荐人ID为空那么就赋值为-1
        if(presenter == null || "".equals(presenter)){
            presenter = "-1";
        }

        //设置参数
        param.put("presenter",presenter);

        //查询增值服务总价
        String addvalueSumPrice = "0";

        if(param.get("addvalue_ids") != null && !"".equals(param.get("addvalue_ids"))){
            addvalueSumPrice = taskInfoDao.findAddvalueSumPriceByAddvalueIds(param.get("addvalue_ids"));
        }
        //设置参数
        param.put("addvalue",addvalueSumPrice);

        //插入任务订单表
        taskInfoDao.addOrderTask(param);


        //取出增值服务ID集合
        String[] addvalue_ids = param.get("addvalue_ids").split(",");

        //循环插入增值服务数据
        for(String addvalue_id : addvalue_ids){

            if(!"".equals(addvalue_id)) {
                param.put("addvalue_id", addvalue_id);

                taskInfoDao.addOrderAddvalue(param);
            }
        }



    }

    @Override
    public void updateItemInfoByItemId(Map<String, String> param) throws Exception {


        //修改项目信息
        taskInfoDao.updateItemInfoByItemId(param);

        //得到任务订单ID
        String order_task_id = taskInfoDao.findOrderTaskIdByItemId(param.get("item_id"));

        //查询增值服务总价
        String addvalueSumPrice = "0";

        if(param.get("addvalue_ids") != null && !"".equals(param.get("addvalue_ids"))){
            addvalueSumPrice = taskInfoDao.findAddvalueSumPriceByAddvalueIds(param.get("addvalue_ids"));
        }

        //设置参数
        param.put("order_task_id",order_task_id);
        param.put("addvalue",addvalueSumPrice);

        //修改任务订单增值服务
        taskInfoDao.updateOrderTaskAddvalueById(param);

        //根据任务订单ID删除增值服务数据
        taskInfoDao.deleteOrderItemAvByOrderTaskId(order_task_id);


        //取出增值服务ID集合
        String[] addvalue_ids = param.get("addvalue_ids").split(",");

        //循环插入增值服务数据
        for(String addvalue_id : addvalue_ids){

            if("".equals(addvalue_id)){
                continue;
            }

            param.put("addvalue_id",addvalue_id);

            taskInfoDao.addOrderAddvalue(param);
        }



    }

    @Override
    public Map<String, Object> updateFindTaskInfoByTaskId(String taskId) throws Exception {

        //
        Map<String, Object> map = taskInfoDao.findTaskInfoByTaskId(taskId);

        if(map != null){

            List<Map<String, String>> list = taskInfoDao.findOrderAddvalueByTaskId(taskId);
            map.put("addvalues",list);

            //如果需求技能ID集不为空，那么就进行翻译处理
            if(map.get("skill") != null && !"".equals(map.get("skill").toString())){

               map.put("skill",taskInfoDao.findSkillNameBySkillIds(map.get("skill").toString()));
            }

            float budget = Float.parseFloat(String.valueOf(map.get("budget")));

            //如果金额大于两千则查询支付定金百分比 并且 判断是否需要托管定金
            if(budget > 2000 && "101001".equals(map.get("is_deposit").toString())){
                map.put("depositScale",commonPayService.findScaleValue( 2 ));
            }else{
                //否则就是百分之百
                map.put("depositScale", "100");
            }



            //放入增值服务费用总计
            float sumAddvalue = 0.0f;
            for(Map<String, String> addMap : list){

                sumAddvalue += Float.parseFloat(addMap.get("price"));

            }
            map.put("sumAddvalue",sumAddvalue);

            Map progress = new HashMap();
            progress.put("item_id",taskId);
            progress.put("progress","105102");
            //改变任务状态为发布项目
            taskInfoDao.updateCurrentProgressByTaskId(progress);

        }

        return map;
    }

    @Override
    public Map<String,Object> updateFindAddvalueByTaskId(String taskId,String userId) throws Exception {

        Map<String,Object> dataMap = new HashMap<String, Object>();

        //查询定金
        Map itemInfo = taskInfoDao.findItemBudgetById(taskId);

        float deposit = 0.0f;
        int is_deposit = (Integer) itemInfo.get("is_deposit");
        int progress = (Integer) itemInfo.get("progress");

        if(101001 == is_deposit && 105104 > progress){

            float budget = Float.parseFloat(itemInfo.get("budget").toString());

            float depositScale = 100f;

            //如果大于两千就查询支付定金比例
            if(budget > 2000){
                depositScale = commonPayService.findScaleValue( 2 );
            }

            deposit = budget * depositScale / 100;

        }

        //查询增值服务
        float addvSumPrice = 0.0f;
        List<Map<String, String>> addvList = taskInfoDao.findOrderAddvalueByTaskId(taskId);
        for(Map<String, String> map : addvList){

            addvSumPrice += Float.parseFloat(map.get("price"));

        }

        //支付总金额
        float totalAmount = deposit + addvSumPrice;

        //查询账户余额
        float wallet = commonPayService.findUserWalletEnough(Integer.parseInt(userId));

        dataMap.put("totalAmount",totalAmount);
        dataMap.put("wallet",wallet);

        Map progressMap = new HashMap();
        progressMap.put("item_id",taskId);
        progressMap.put("progress","105103");
        //改变任务状态为托管定金
        taskInfoDao.updateCurrentProgressByTaskId(progressMap);

        return dataMap;
    }


    @Override
    public boolean isRaceInfoProgress(String raceId) throws Exception {

        //项目进度
        Map itemInfo = taskInfoDao.findItemBudgetById(raceId);

        int progress = (Integer) itemInfo.get("progress");
        if(progress > 105103){
            return false;
        }

        return true;

    }

    @Override
    public boolean addvaluePayByAlipay(String task_id,String user_id) throws Exception {


        return false;
    }

    @Override
    public boolean addvaluePayByPaypay(String task_id,String user_id) throws Exception {


        return false;
    }

    @Override
    public Map<String,Object> addvaluePayByBalance(String item_id,String user_id) throws Exception {

        //返回数据Map
        Map<String,Object> dataMap = new HashMap<String, Object>();


        //查询定金
        Map itemInfo = taskInfoDao.findItemBudgetById(item_id);

        int progress = (Integer) itemInfo.get("progress");
        if(105103 != progress){


            dataMap.put("static","4");
            dataMap.put("msg","该项目已进入审核阶段，不能再支付费用了！");

            return dataMap;

        }

        float deposit = 0.0f;
        int is_deposit = (Integer) itemInfo.get("is_deposit");

        if(101001 == is_deposit && 105104 > progress){

            float budget = Float.parseFloat(itemInfo.get("budget").toString());

            float depositScale = 100f;

            //如果大于两千就查询支付定金比例
            if(budget > 2000){
                depositScale = commonPayService.findScaleValue( 2 );
            }

            deposit = budget * depositScale / 100;

        }

        //放入项目名
        dataMap.put("title",itemInfo.get("title"));

        //查询出该任务所有增值服务订单ID和价格
        List<Map<String, String>> list = taskInfoDao.findPriceByTaskId(item_id);

        float addvSumPrice = 0.0f;
        for(Map<String,String> addvalue : list){

            addvSumPrice += Float.parseFloat( addvalue.get("price") );
        }

        //支付总金额
        float totalAmount = deposit + addvSumPrice;


        //等到任务订单ID
        Integer order_task_id = Integer.parseInt(String.valueOf(taskInfoDao.findOrderTaskIdByItemId(item_id)));

        //查询用户账户是否充足
        boolean enoughFlag = commonPayService.isUserWalletEnough(totalAmount,Integer.parseInt(user_id));

        //如果为false 表示用户账户余额不足
        if(!enoughFlag){

            throw new InsufficientBalanceException("支付失败，账户余额不足或金额被冻结，抛出自定义异常!用户ID："+ user_id + "；支付金额：" + addvSumPrice +"；支付类型：" + 112112);
        }

        //支付 类型：112112 表示增值服务支出
        boolean payFlag = commonPayService.updateDeductUserWalletByUserId(addvSumPrice,Integer.parseInt(user_id),112112);

        //如果支付标识为false 那么就表示没有支付成功
        if(!payFlag){

            throw new InsufficientBalanceException("支付失败，账户余额不足，抛出自定义异常!用户ID："+ user_id + "；支付金额：" + addvSumPrice +"；支付类型：" + 112112);
        }

        //冻结，类型：112110 表示冻结金额
        boolean blockedFlag = commonPayService.updateBlockedUserWalletByUserId(deposit,Integer.parseInt(user_id),112110,order_task_id,true,true);

        if(!blockedFlag){

            throw new InsufficientBalanceException("支付失败，账户余额不足，抛出自定义异常!用户ID："+ user_id + "；支付金额：" + deposit +"；支付类型：" + 112110);
        }


        if(itemInfo.get("use_fee") == null ){
            itemInfo.put("use_fee",101002);
        }

        int use_fee = Integer.parseInt(String.valueOf( itemInfo.get("use_fee") ));

        //101001 为是
        if(101001 == use_fee){

            //查询手续费卡数量
            int feeNum = taskInfoDao.findUserFeeNumByUserId(Integer.parseInt(user_id) );

            if(feeNum > 0){

                //扣除用户当前手续费卡
                taskInfoDao.updateUserFeeNumByUserId(user_id);

                //手续费使用记录Map
                Map user_feeMap = new HashMap();

                user_feeMap.put("user_id",user_id);
                user_feeMap.put("num",1);
                user_feeMap.put("type",132103);
                //需要得到竞赛订单ID
                user_feeMap.put("remark","消耗零手续费卡，项目ID：" + item_id);

                //写入0手续费卡使用记录
                taskInfoDao.insertUserFee(user_feeMap);


            }else{

                throw new FeeCardNotEnoughException("零手续费卡不足，抛出自定义异常！用户ID："+ user_id + "，项目ID：" + item_id);

            }

        }





        Map progressMap = new HashMap();
        progressMap.put("item_id",item_id);
        progressMap.put("progress","105104");

        //改变任务状态为审核中
        taskInfoDao.updateCurrentProgressByTaskId(progressMap);

        for(Map<String,String> addvalue : list){

            //改变增值服务状态和价格
            taskInfoDao.updateOrderAddvalueStatus(addvalue);
        }


        dataMap.put("static","0");
        dataMap.put("msg","支付成功！");

        return dataMap;

    }

}
